import React from 'react';
import {
  StyleSheet,
  Text,
  View,
  FlatList,
  ActivityIndicator,
} from 'react-native';
import Fetching from './Fetching';
export default class QList extends React.PureComponent {
  static defaultProps = {
    ...FlatList.defaultProps,
    keyExtractor: (_, index) => `${index}`,
    onEndReachedThreshold: 0.1,
  };
  state = {
    loading: false,
    finished: false,
    items: [],
    page: 0,
    error: null,
  };

  async fetchItems() {
    try {
      const {fetch} = this.props;
      const {items, page} = this.state;
      this.setState({loading: true});
      console.log('fetchItems', page);
      const {items: newItems = [], end = false} =
        (fetch && (await fetch(page))) || {};
      if (this.unmounted) {
        return;
      }
      this.setState({
        items: items.concat(newItems),
        finished: end,
        loading: false,
        page: page + 1,
      });
    } catch (error) {
      this.setState({error});
    }
  }
  componentWillUnmount() {
    this.unmounted = true;
  }
  genFooterComponent() {
    const {ListFooterComponent} = this.props;
    if (ListFooterComponent) {
      return ListFooterComponent;
    }
    const {finished, error} = this.state;

    return (
      <>
        <View style={styles.footerBar}>
          {error && <Text>{error}</Text>}
          {finished && !error ? (
            <Text style={styles.text}>End</Text>
          ) : (
            <>
              <ActivityIndicator />
              <Text style={styles.text}>Loading...</Text>
            </>
          )}
        </View>
      </>
    );
  }
  isEmpty() {
    const {items, finished} = this.state;
    return finished && items && items.length <= 0;
  }

  reload(){
    this.setState({
      loading: false,
      finished: false,
      items: [],
      page: 0,
      error: null,
    }, ()=>{
      if(this.fetching){
        this.fetching.reload()
      }
      this.checkCanLoad();
    })
  }

  checkCanLoad() {
    const {loading, finished, items} = this.state;
    console.log('checkCanLoad', items);
    if (finished || loading) {
      return;
    }
    this.fetchItems();
  }
  render() {
    const {items} = this.state;
    return (
      <Fetching ref={ref => this.fetching = ref} fetch={this.fetchItems.bind(this)}>
        <FlatList
          {...this.props}
          data={items}
          ListFooterComponent={this.genFooterComponent()}
          onEndReached={this.checkCanLoad.bind(this)}
        />
      </Fetching>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  footerBar: {
    justifyContent: 'center',
    height: 40,
    alignItems: 'center',
    flexDirection: 'row',
  },
  text: {
    marginLeft: 10,
    marginRight: 10,
  },
});
